package com.chidopi.market.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.struts.upload.FormFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileHelper {
	
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmsss");
	
	private static Logger logger = LoggerFactory.getLogger(FileHelper.class);
	
	public static String getRandomTimeString (String prefix){
		String string = sdf.format(new Date());
		Random r = new Random();
		string = prefix + (r.nextInt(8999)+ 1000) + string;
		return string;
		
	}
	public static void writeFile(FormFile file, String dest)throws Exception{

		InputStream input = null;
		FileOutputStream fr = new FileOutputStream(dest);
		try {
			input = file.getInputStream();
			IOUtils.copy(input, fr);
			input.close();
			fr.close();
		} catch (Exception e) {
			logger.warn("write file failure : " + dest);
		} finally {
			IOUtils.closeQuietly(input);
			IOUtils.closeQuietly(fr);
		}
		
	}
	
	public static String getFileSuffix(String filename){
		int index = filename.lastIndexOf('.');
		if(index == -1) return "";
		return filename.substring(filename.lastIndexOf('.')+1);
	}
	
	public static void deleteFile(String dest) {
		File file = new File(dest);
		
		Boolean result = false;
		int delCount = 0;
		while (!result && delCount++ < 10) {
			logger.warn("try to delete file " + dest + " count: " + delCount);
			System.gc();
			result = file.delete();
		}
//		try {
//			//FileUtils.deleteQuietly(file);
//		} catch (Exception e) {
//			logger.warn("delete file failure : " + dest);
//
//			
//		}
	}
	public static void writeImageToResponse(HttpServletResponse response,
			String path) {
		String type =  getFileSuffix(path);
		File file = new File(path);
		if(file.exists() && file.isFile()){
			response.setContentType("image/" + type);
			OutputStream out = null;
			InputStream in = null;
			try {
				out = response.getOutputStream();
				in = new FileInputStream(file);
				IOUtils.copy(in, out);
				
				out.flush();
				in.close();
				out.close();
				
			} catch (IOException e) {
				logger.warn("write Image failure: " + path);
			}finally{
				IOUtils.closeQuietly(in);
				IOUtils.closeQuietly(out);
			}			
		}		
	}
	
	public static void downloadFile(HttpServletResponse response, String path, String filename) {
		File file = new File(path);
		if(file.exists() && file.isFile()){
			response.setContentType("application/octet-stream");
			String name = filename;
			try {
				name = new String(filename.getBytes("gb2312"), "ISO8859-1");
//				name = URLEncoder.encode(filename,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				logger.warn("name error: " + e);
			}
			response.addHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
			
			OutputStream out = null;
			InputStream in = null;
			try {
				out = response.getOutputStream();
				in = new FileInputStream(file);
				IOUtils.copy(in, out);
				
				out.flush();
				in.close();
				out.close();
				
			} catch (IOException e) {
				logger.warn("DownFile "+ path +" failure, " + e );
			}finally{
				IOUtils.closeQuietly(in);
				IOUtils.closeQuietly(out);
			}	
			
			
		}
		
	}
	public static void checkPath(String path) {
		try {
			FileUtils.forceMkdir(new File(path));
		} catch (IOException e) {
			logger.warn("makeDir [" + path + "] erroe " , e);
		}
	}
	
}
